<script setup lang="ts">
import { ref } from 'vue'
import cityListJson from '@/constant/city-list'
import { ICity } from './type'

const emit = defineEmits<{
  (e: 'changeArea', value: string): void
}>()

const active = ref(false)
const toggleDialog = () => {
  active.value = !active.value
}

const cityList = ref(cityListJson)

const locationName = ref('北京 北京市 东城区')
//当前显示的区域

const lastlocationName = ref('')

//用来保存上次选中的区域

const chooseArea = (city: ICity) => {
  if (city.level === 0) {
    //重置上次区域
    lastlocationName.value = ''
  }
  lastlocationName.value = lastlocationName.value + ' ' + city.name
  if (city.areaList) {
    cityList.value = []
    cityList.value.push(...city.areaList)
    return
  }
  locationName.value = lastlocationName.value
  //表示已经完成了选择 让显示区域等于 上次选中区域
  cityList.value = cityListJson
  active.value = false
}
</script>

<template>
  <div class="city" ref="target">
    <div class="select" @click="toggleDialog" :class="{ active }">
      <span class="placeholder" v-if="!locationName">请选择配送地址</span>
      <span class="value" v-else>{{ locationName }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <div class="option" v-if="active">
      <span
        class="ellipsis"
        v-for="city in cityList"
        :key="city.code"
        @click="chooseArea(city)"
        >{{ city.name }}</span
      >
    </div>
  </div>
</template>

<style lang="less" scoped>
.city {
  display: inline-block;
  position: relative;
  z-index: 400;
  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;
    &.active {
      background: #fff;
    }
    .placeholder {
      color: #999;
    }
    .value {
      color: #666;
      font-size: 12px;
    }
    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }
  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    > span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;
      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>
